/**
 * bindAccount.html
 */
$(function() {
	// 回车登录
	$(document).keyup(
		function(event) {
			if (event.keyCode == 13) {
				if ($("#bindAccount").hasClass("active")) {
					userLogin();
					return;
				}
			}
		});

	// 如果后台有传递过来地址栏 则
	$("#bindAccount").click(function() {
		if (!$(this).hasClass("active")) {
			return;
		}
		userLogin();
	});
	$("#code_img,#next").click(refreshCheckCode);
	refreshCheckCode();

	var msg = getParentUrlParam("msg");
	if (!$.isEmptyObject(msg) && $.isEmptyObject(getUrlParam("nomsg"))) {
		showUserErrMsg(msg);
		$("#user").click();
	}
	
	$(".bind_phone_btn").click(bindPhone);
})

// 用户账户登录
function userLogin() {
	var u = $("#username_input").val();
	var p = $("#password_input").val();
	var c = $("#checkcode_text").val();
	var s = getParentUrlParam("service");
	var isOk = true;
	if (isNull(u)) {
		showUserErrMsg("请输入用户名。");
		return;
		isOk = false;
	}
	if (isNull(p)) {
		showUserErrMsg("请输入密码。");
		return;
		isOk = false;
	}
	if (isNull(c)) {
		showUserErrMsg("请输入验证码。");
		return;
		isOk = false;
	}
	if (!isOk) {
		return;
	}
	document.cookie = "login=" + escape(u) + ";path=/";
	var curUrl = parent.location.href.replace(/(^|\\?|&)msg=([^&]*)/, "")
			.replace(/(^|\\?|&)un=([^&]*)/, "");
	if (curUrl.indexOf("?") > -1) {
		curUrl += "&un=" + u;
	} else {
		curUrl += "?un=" + u;
	}
	// var url = casLoginApi + "?un=" + u + "&pd=" + p + "&checkcode=" + c;// +
	// "&fail=" + encodeURIComponent(curUrl);
	// url += !$.isEmptyObject(s)?("&service="+s):"";
	// parent.location.href=url;
	var url = casLoginApi;
	//url += !$.isEmptyObject(s) ? ("&service=" + s) : "";

	var body = $(parent.document.body);
	var form = $("<form method='post'></form>");
	form.attr({
		"action" : url
	});
	var input;

	input = $("<input type='hidden'>");
	input.attr({
		"name" : "username"
	});
	input.val(u);
	form.append(input);

	input = $("<input type='password'>");
	input.attr({
		"name" : "password"
	});
	input.val(p);
	form.append(input);

	input = $("<input type='hidden'>");
	input.attr({
		"name" : "checkcode"
	});
	input.val(c);
	form.append(input);
	
	if(!$.isEmptyObject(s)){
    	input = $("<input type='hidden'>");
    	input.attr({"name":"service"});
    	input.val(s);
    	form.append(input);
    }
	
	form.appendTo(body);
	form.submit();
}

//绑定手机
function bindPhone() {
	var url = "./binding.html";
	document.location.href = url;
}

// 刷新验证码
function refreshCheckCode() {
	$("#code_img").attr("src", '/cas/captcha.jpg?tm=' + Math.random());
}